<?php

namespace app\admin\controller\wanlshop;

use addons\wanlshop\library\WanlPay\WanlPay;
use app\admin\model\wanlshop\ShopEarnestLog;
use app\common\controller\Backend;
use app\common\model\Config;
use think\Db;
use think\Exception;

use think\exception\PDOException;
use think\exception\ValidateException;
use think\Log;
use think\Model;
use WanlPay\Yansongda\Pay;

/**
 * 认证管理
 *
 * @icon fa fa-circle-o
 */
class Auth extends Backend
{
    
    /**
     * Auth模型对象
     * @var \app\admin\model\wanlshop\Auth
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\Auth;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("verifyList", $this->model->getVerifyList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
	/**
	 * 详情
	 */
	public function detail($ids = null)
	{
		$row = $this->model->get($ids);
		if (!$row) {
		    $this->error(__('No Results were found'));
		}
		$this->view->assign("row", $row);
		return $this->view->fetch();
	}
	
	/**
	 * 同意
	 */
	public function agree($ids = null)
	{
		$row = $this->model->get($ids);
		if (!$row) {
		    $this->error(__('No Results were found'));
		}
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds)) {
		    if (!in_array($row[$this->dataLimitField], $adminIds)) {
		        $this->error(__('You have no permission'));
		    }
		}
		if (in_array($row['verify'],[3,5])) {
		     $this->error(__('已审核过本店铺，请不要重复审核！'));
		}
		if ($this->request->isPost()) {
			$result = false;
			Db::startTrans();
			try {
			    //是否采用模型验证
			    if ($this->modelValidate) {
			        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
			        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
			        $row->validateFailException(true)->validate($validate);
			    }

                // 审核通过
			    if(Config::getEarnestMoney() > 0){
                    $result = $row->allowField(true)->save(['verify' => 5]);
                }else{
                    $result = $row->allowField(true)->save(['verify' => 3]);
                }

				if($row['verify'] != 4){
					// 新增店铺
					$shop = model('app\admin\model\wanlshop\Shop');
					$shop->user_id = $row['user_id'];
					$shop->state = $row['state'];
					$shop->shopname = $row['shopname'];
					$shop->avatar = $row['avatar'];
					$shop->bio = $row['content'];
					$shop->description = $row['bio'];
					$shop->city = $row['city'];
                    $shop->phone = $row['mobile'];
                    $shop->address = $row['address'];
                    $shop->lng = $row['lng'];
                    $shop->lat = $row['lat'];
					$shop->verify = $row['verify'];
					$shop->open_hours = '00:00-23:59';
					// 新增店铺配置
					if($shop->save()){
						$config = model('app\index\model\wanlshop\ShopConfig');
						$config->shop_id = $shop->id;
						$result = $config->save();
					}
				}
			    Db::commit();
			} catch (ValidateException $e) {
			    Db::rollback();
			    $this->error($e->getMessage());
			} catch (PDOException $e) {
			    Db::rollback();
			    $this->error($e->getMessage());
			} catch (Exception $e) {
			    Db::rollback();
			    $this->error($e->getMessage());
			}
			if ($result !== false) {
			    $this->success();
			} else {
			    $this->error(__('No rows were updated'));
			}
		}
		$this->view->assign("row", $row);
		return $this->view->fetch();
	}
	
	/**
	 * 拒绝
	 */
	public function refuse($ids = null)
	{
		$row = $this->model->get($ids);
		if (!$row) {
		    $this->error(__('No Results were found'));
		}
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds)) {
		    if (!in_array($row[$this->dataLimitField], $adminIds)) {
		        $this->error(__('You have no permission'));
		    }
		}
		if ($this->request->isPost()) {
		    $params = $this->request->post("row/a");
		    if ($params) {
		        $params = $this->preExcludeFields($params);
		        $result = false;
		        Db::startTrans();
		        try {
		            //是否采用模型验证
		            if ($this->modelValidate) {
		                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
		                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
		                $row->validateFailException(true)->validate($validate);
		            }
					$params['verify'] = 4;
		            $result = $row->allowField(true)->save($params);
		            Db::commit();
		        } catch (ValidateException $e) {
		            Db::rollback();
		            $this->error($e->getMessage());
		        } catch (PDOException $e) {
		            Db::rollback();
		            $this->error($e->getMessage());
		        } catch (Exception $e) {
		            Db::rollback();
		            $this->error($e->getMessage());
		        }
		        if ($result !== false) {
		            $this->success();
		        } else {
		            $this->error(__('No rows were updated'));
		        }
		    }
		    $this->error(__('Parameter %s can not be empty', ''));
		}
		$this->view->assign("row", $row);
		return $this->view->fetch();
	}


    /**
     * 同意
     */
    public function refund($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $EarnestLog = (new ShopEarnestLog())->where(['user_id'=>$row['user_id']])->find();

        if($EarnestLog && $EarnestLog['status'] == 'paid'){
            $out_refund_no =  'TK'.date("Ymdhis") . sprintf("%08d", $this->auth->id) . mt_rand(10000, 99999);
            $EarnestLog->out_refund_no = $out_refund_no;
            $EarnestLog->save();

            $money =  $EarnestLog['payamount'];
            $order['out_trade_no'] = $EarnestLog['orderid'];  //商户订单号
            $order['out_refund_no'] =$out_refund_no; //商家退款订单号
            $order['total_fee'] = bcmul($money, 100, 0); // 订单金额
            $order['refund_fee'] = bcmul($money, 100, 0);
            $order['refund_desc'] = '保证金订单（订单号：'.$EarnestLog['orderid'].'）退款微信账户￥'.$money.'元。';
//            $order['type'] = 'wechat';
//            $order['method'] = 'miniapp';

            $order['type'] = 'miniapp';
            $payConfig = (new WanlPay())->getConfig('wechat');
            $payConfig['notify_url'] = str_replace("notify", "earnest_notify_refund", $payConfig['notify_url']);
            $wanlpay = Pay::wechat($payConfig)->refund($order);
            if($wanlpay->result_code == 'SUCCESS'){
                $this->success('提交成功');
            }else{
                $this->error('失败成功');
            }
        }else{
            $this->error('你目前没有支付保证金');
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
	
}
